/***** BEGIN LICENSE BLOCK *****
 Version: MPL 1.1
 
 The contents of this file are subject to the Mozilla Public License Version 
 1.1 (the "License"); you may not use this file except in compliance with 
 the License. You may obtain a copy of the License at 
 http://www.mozilla.org/MPL/
 
 Software distributed under the License is distributed on an "AS IS" basis,
 WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 for the specific language governing rights and limitations under the
 License.
 
 The Original Code is GureGipuzkoa Extension.
 
 The Initial Developer of the Original Code is Asier Sarasua Garmendia.
 Portions created by the Initial Developer are Copyright (C) 2009
 the Initial Developer. All Rights Reserved.
 
 Contributor(s):
    Asier Sarasua Garmendia <asier.sarasua@gmail.com>
    Julen Ruiz Aizpuru <julenx@gmail.com>
    Juanan Pereira Varela <juanan@diariolinux.com>
 
 ***** END LICENSE BLOCK *****/


/* Opens the account management window: manage more than one account
function openAccountsDialog() {
  var dialogURL = "chrome://guregipuzkoa/content/login.xul";
  window.openDialog(dialogURL, "", "chrome,modal,resizable");
}
*/

const ggAccounts = {
  hostname: 'chrome://guregipuzkoa',

  formSubmitURL: null,

  httprealm: "Gure Gipuzkoa Login",

  onLogin: function() {
    if (gureGipuzkoaUtils.prefManager.getCharPref("guregipuzkoa.user.apikey") == "") {
      gureGipuzkoaUIUtils.prompt.alert(null, gureGipuzkoaStrUtils.strBundle.getString("WinTitle"),
                             gureGipuzkoaStrUtils.strBundle.getString("APINo") );
      gureGipuzkoa.openHelp("chrome://guregipuzkoa/locale/help/apikey.html");
      return false;
    }
    var myLoginManager = Components.classes["@mozilla.org/login-manager;1"]
                                   .getService(Components.interfaces.nsILoginManager);

    var nsLoginInfo = new Components.Constructor("@mozilla.org/login-manager/loginInfo;1",
                                                 Components.interfaces.nsILoginInfo, "init");

    var msg = gureGipuzkoaStrUtils.strBundle.getString("AddLogin");
    var user = {value: ""};
    var pass = {value: ""};
    var result = gureGipuzkoaUIUtils.prompt.promptUsernameAndPassword(window,
                                                            gureGipuzkoaStrUtils.strBundle.getString("WinTitle"),
                                                            msg, user, pass, "", {value:false});
    if (result) {
      user = user.value;
      pass = pass.value;
      //document.getElementById("browser").setAttribute('wait-cursor', true);

      gureGipuzkoa.apiCall(
        {method: 'gg.auth.getToken', username: user, password: pass},
        function(xhr) {
          var extLoginInfo = new nsLoginInfo('chrome://guregipuzkoa', null, 'Gure Gipuzkoa Login',
                                             user, pass, "", "");
          myLoginManager.addLogin(extLoginInfo);
          var msg = gureGipuzkoaStrUtils.strBundle.getString("LoginYes");
          gureGipuzkoaUIUtils.prompt.alert(null, gureGipuzkoaStrUtils.strBundle.getString("WinTitle"), msg);
          // Function to switch login buttons and label
          ggAccounts.switchLogin(user, "true");

          // Check the upload button in case there are uploads waiting
          ggUpload.checkUploadButton();

          ggAccounts.getId(user);

          // Check login information in gureGipuzkoa
          ggAccounts.checkLogin();

          // Retrieve first token
          gureGipuzkoa.getToken();
        },
        function() {
          var msg = gureGipuzkoaStrUtils.strBundle.getString("LoginNo");
          gureGipuzkoaUIUtils.prompt.alert(null, gureGipuzkoaStrUtils.strBundle.getString("WinTitle"), msg);
        });
    }
  },


  onLogout: function() {
    var username = '';
    var currentUser = document.getElementById('gg-currentuser');
    username = currentUser.value;

    try {
      // Get Login Manager 
      var passwordManager = Components.classes["@mozilla.org/login-manager;1"]
                                      .getService(Components.interfaces.nsILoginManager);

      // Find users for this extension 
      var logins = passwordManager.findLogins({}, this.hostname, this.formSubmitURL, this.httprealm);
     
      for (var i = 0; i < logins.length; i++) {
        if (logins[i].username == username) {
          passwordManager.removeLogin(logins[i]);
          break;
        }
      }
    }
    catch(ex) {
      // This will only happen if there is no nsILoginManager component class
    }
    // Function to switch login buttons and label
    var logoutStr = gureGipuzkoaStrUtils.strBundle.getString("LoggedOut");
    this.switchLogin(logoutStr, "false");

    // Check the upload button in case there are uploads waiting
    ggUpload.checkUploadButton();

    // Check login information in gureGipuzkoa
    this.checkLogin();

    // Workaround to collapse the logout button
    var logoutButton = document.getElementById('gg-logoutbutton');
    logoutButton.setAttribute('collapsed', "true");
    gureGipuzkoaUtils.prefManager.setCharPref("guregipuzkoa.user.id", "");
  },


  switchLogin: function(usr, val) {
    //Switchs login buttons and label
    var currentUser = document.getElementById('gg-currentuser');
    currentUser.value = usr;
    var loginButton = document.getElementById('gg-loginbutton');
    loginButton.setAttribute('collapsed', val);
    var logoutButton = document.getElementById('gg-logoutbutton');
    logoutButton.setAttribute('collapsed', !val);
  },


  getId: function(usr) {
    gureGipuzkoa.apiCall(
      {method: 'gg.people.findByUsername', username: usr},
      function(xhr) {
        var userId = xhr.responseXML.getElementsByTagName("user")[0].attributes[0].value;
        gureGipuzkoaUtils.prefManager.setCharPref("guregipuzkoa.user.id", userId);
      },
      function() {});
  },


  /* Checks login information stored in gureGipuzkoa 
   */
  checkLogin:
    function() {
      var login = this.getLogin();
      if (!login) {
        gureGipuzkoa.username = "";
        gureGipuzkoa.password = "";
      } else {
        gureGipuzkoa.username = login.user;
        gureGipuzkoa.password = login.pass;
      }
  },


  /* Returns an object with the login information
   */
  getLogin:
    function() {
      var myLoginManager = Components.classes["@mozilla.org/login-manager;1"]
                                      .getService(Components.interfaces.nsILoginManager);
      var logins = myLoginManager.findLogins({}, this.hostname,
                                             this.formSubmitURL, this.httprealm);
      if (logins.length == 0) {
        return false;
      } else {
        return { user: logins[0].username,
                 pass: logins[0].password }
      }
  },

}

